package com.ctshk.rpc.custom.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.NumberHeadCode;
import com.ctshk.common.enums.SystemBusinessType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.AppReq;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.CharUtil;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.cms.service.INoticeService;
import com.ctshk.rpc.custom.dto.client.ClientAreaDTO;
import com.ctshk.rpc.custom.dto.client.ClientInquiryDetailDTO;
import com.ctshk.rpc.custom.dto.client.ClientInquiryListDTO;
import com.ctshk.rpc.custom.dto.client.ClientInquiryRequireListDTO;
import com.ctshk.rpc.custom.entity.CustomizedInquiry;
import com.ctshk.rpc.custom.entity.CustomizedQuotationTouristType;
import com.ctshk.rpc.custom.entity.CustomizedTripScheduleInformation;
import com.ctshk.rpc.custom.json.ContactTelephoneJson;
import com.ctshk.rpc.custom.json.InternalRemarkJson;
import com.ctshk.rpc.custom.mapper.CustomizedInquiryMapper;
import com.ctshk.rpc.custom.mapper.CustomizedInquiryServiceRequireMapper;
import com.ctshk.rpc.custom.mapper.CustomizedQuotationTouristTypeMapper;
import com.ctshk.rpc.custom.mapper.CustomizedTripScheduleInformationMapper;
import com.ctshk.rpc.custom.req.QuotationTouristTypeReq;
import com.ctshk.rpc.custom.req.TravelDaysReq;
import com.ctshk.rpc.custom.req.client.ClientInquiryDetailReq;
import com.ctshk.rpc.custom.req.client.ClientInquiryListReq;
import com.ctshk.rpc.custom.req.client.ClientNoticeListDTO;
import com.ctshk.rpc.custom.req.inquiry.InquiryRequireReq;
import com.ctshk.rpc.custom.req.inquiry.InquiryTourInformationReq;
import com.ctshk.rpc.custom.service.ICustomizedTripScheduleInformationService;
import com.ctshk.rpc.system.dto.AreaDTO;
import com.ctshk.rpc.system.dto.MainDataRowFieldDataDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.req.AreaQueryReq;
import com.ctshk.rpc.system.req.DispatchOrderRuleGetUserReq;
import com.ctshk.rpc.system.req.MainDataRowFieldDataReq;
import com.ctshk.rpc.system.service.IDispatchOrderRuleService;
import com.ctshk.rpc.system.service.IMainDataTableService;
import com.ctshk.rpc.system.service.ISysAreaService;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.user.service.IUserSmsService;
import com.ctshk.rpc.user.service.IUserValidateService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 定制旅游项目 定制旅游信息 实现类
 * </p>
 *
 * @author 于松明
 * @since 2021-04-22
 */
@DubboService
public class CustomizedTripScheduleInformationServiceImpl extends ServiceImpl<CustomizedTripScheduleInformationMapper, CustomizedTripScheduleInformation> implements ICustomizedTripScheduleInformationService {

    @Autowired
    private CustomizedInquiryMapper inquiryMapper;
    @Autowired
    private CustomizedInquiryServiceRequireMapper inquiryServiceRequireMapper;
    //旅客类型mapper接口
    @Autowired
    private CustomizedQuotationTouristTypeMapper quotationTouristTypeMapper;

    @DubboReference
    private IMainDataTableService mainDataTableService;
    @DubboReference
    private ISysAreaService sysAreaService;
    @DubboReference
    private INoticeService noticeService;
    @DubboReference
    private IUserValidateService userValidateService;
    @DubboReference
    private IUserSmsService userSmsService;
    @DubboReference
    private IDispatchOrderRuleService dispatchOrderRuleService;
    @DubboReference
    private ISysUserService sysUserService;


    /**
     * 定制游下单（C端）
     * @param req
     * @param appReq
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(InquiryTourInformationReq req, AppReq appReq){
        //校验验证码
        try {
            boolean checkCode = userValidateService.checkCode(req.getContactTelAreaCode(), req.getContactTelephones(), req.getCode());
            if (!checkCode){
                throw new BusinessException(SystemError.SYS_435);
            }
        }catch (Exception e){
            throw new BusinessException(SystemError.SYS_435);
        }
        CustomizedInquiry inquiry = null;
        LocalDateTime now = LocalDateTime.now();
        //编辑
        if (req.getId() != null){
            inquiry = inquiryMapper.selectById(req.getId());
            if (inquiry == null || Objects.equals(inquiry.getIsDeleted(),1)){
                throw new BusinessException(SystemError.ZLW_CUSTOM_ERROR_30001);
            }
            if (req.getUserId() != null){
                inquiry.setModifiedId(req.getUserId());
            }
            inquiry.setGmtModified(now);
        }else{
            //新增
            inquiry = new CustomizedInquiry();
            if (Objects.equals(req.getTravelType(),3)){
                inquiry.setDepartType(5);
            }else{
                inquiry.setDepartType(3);
            }
            inquiry.setId(SnowflakeIdWorker.nextId());
            String inquiryNumber = NumberHeadCode.INQUIRY.getCode() + DateUtil.fmtNum(LocalDate.now()) + RandomUtil.randomNumbers(4);
            inquiry.setInquiryNumber(inquiryNumber);
            inquiry.setCustomerType(1);
            //查詢編號
            String queryNumber = CharUtil.getNumber(4, 4);
            inquiry.setQueryNumber(queryNumber);
            inquiry.setInquiryStatus(2);
            if (req.getUserId() != null){
                inquiry.setUserId(req.getUserId());
            }
            //OP默认admin
            inquiry.setOpId(1344284712813568L);
            inquiry.setOpNumber("0000001");
            inquiry.setOpName("周杰伦");
            //获取销售
            UserDTO saleMan = getSaleMan(appReq.getCompanyType());
            inquiry.setSalespersonId(saleMan.getId());
            inquiry.setSalespersonName(saleMan.getFullName());
            inquiry.setSalespersonNumber(saleMan.getEmployeeNumber());
            inquiry.setGmtCreate(now);
            inquiry.setIsDeleted(0);
        }
        //标题展示，字符拼接
        String title = req.getDeparturePlace()  + req.getTravelDaysReq().getDays() + "天" + req.getTravelDaysReq().getNights() + "晚";
        inquiry.setInquiryTitle(title);
        inquiry.setTravelType(req.getTravelType());
        StringBuffer destination = new StringBuffer();
        for (int i = 0;i < req.getDestination().size();i++) {
            ClientAreaDTO clientAreaDTO = req.getDestination().get(i);
            destination.append(clientAreaDTO.getCityTraditional());
            if (i < (req.getDestination().size() - 1) && req.getDestination().size() != 1){
                destination.append(",");
            }
        }
        inquiry.setDestination(destination.toString());
        inquiry.setDestinationJson(JSON.toJSONString(req.getDestination()));
        /*inquiry.setDestinationId(req.getDestinationId());
        inquiry.setDestination(req.getDestination());*/
        inquiry.setDeparturePlaceId(req.getDeparturePlaceId());
        inquiry.setDeparturePlace(req.getDeparturePlace());
        inquiry.setDepartureDate(req.getDepartureDate());
        inquiry.setTravelDays(req.getTravelDaysReq().getDays());
        inquiry.setNightDays(req.getTravelDaysReq().getNights());

        //人数计算 总人数
        int totalPeopleNum = 0;
        if (CollUtil.isNotEmpty(req.getTouristTypes())) {
            totalPeopleNum = req.getTouristTypes().stream().mapToInt(QuotationTouristTypeReq::getPeopleNum).sum();
        }
        inquiry.setTotalPeopleNum(totalPeopleNum);

        // 人均价格结果 计算
    //    BigDecimal divide = req.getCapitaBudget().divide(BigDecimal.valueOf(totalPeopleNum),2,BigDecimal.ROUND_HALF_UP);
        inquiry.setCapitaBudget(req.getCapitaBudget());

        // 记录旅客类型(成人,老人,小孩等信息)
        if (CollUtil.isNotEmpty(req.getTouristTypes())) {
            List<CustomizedQuotationTouristType> touristTypeList = new ArrayList<>();
            for (QuotationTouristTypeReq quotationTouristTypeReq : req.getTouristTypes()){
                CustomizedQuotationTouristType quotationTouristType = EntityUtil.copy(quotationTouristTypeReq, CustomizedQuotationTouristType.class);
                quotationTouristType.setId(SnowflakeIdWorker.nextId());
                quotationTouristType.setInquiryId(inquiry.getId());
                quotationTouristType.setMainDataId(quotationTouristTypeReq.getValue());
                quotationTouristType.setName(quotationTouristTypeReq.getLabel());
                quotationTouristType.setPeopleNum(quotationTouristType.getPeopleNum());
                quotationTouristType.setGmtCreate(now);
                quotationTouristType.setIsDeleted(0);
                if (req.getUserId() != null){
                    quotationTouristType.setCreateId(req.getUserId());
                }
                touristTypeList.add(quotationTouristType);
            }
            if (touristTypeList.size() > 0){
                Integer batch = quotationTouristTypeMapper.insertBatchSomeColumn(touristTypeList);
                if (batch < touristTypeList.size()){
                    throw new BusinessException(SystemError.ZLW_CUSTOM_ERROR_30000);
                }
            }
        }
        inquiry.setContactName(req.getContactName());
        List<ContactTelephoneJson> contactTelephoneJsonList = new ArrayList<>();
        ContactTelephoneJson contactTelephoneJson = new ContactTelephoneJson();
        contactTelephoneJson.setContactTelAreaCode(req.getContactTelAreaCode());
        contactTelephoneJson.setContactTelephones(req.getContactTelephones());
        contactTelephoneJsonList.add(contactTelephoneJson);
        //记录用户信息
        inquiry.setPhoneCode(req.getContactTelAreaCode());
        inquiry.setPhone(req.getContactTelephones());
        inquiry.setContactTelephones(JSON.toJSONString(contactTelephoneJsonList));
        inquiry.setContactEmail(req.getContactEmail());
        //服务要求
        if (CollectionUtils.isNotEmpty(req.getRequireList())){
            inquiry.setThemeJson(JSON.toJSONString(req.getRequireList()));
        }
        inquiry.setInternalRemark(req.getInternalRemark());
        int insert = inquiryMapper.insert(inquiry);
        if (insert <= 0){
            throw new BusinessException(SystemError.ZLW_CUSTOM_ERROR_30000);
        }
        //发送短信通知
        Map<String,String> smsParam = new HashMap<>();
        smsParam.put("orderid",inquiry.getInquiryNumber());
        smsParam.put("code",inquiry.getQueryNumber());
        Result result = userSmsService.sendOrderSms(SystemBusinessType.OUTBOUND_CUSTOMIZATION.getCode(), req.getContactTelAreaCode(), req.getContactTelephones(), smsParam);
        if (result == null || !result.isSuccess()){
            throw new BusinessException(SystemError.SYS_436);
        }
        return Result.success(inquiry.getId());
    }

    /**
     * 获取销售
     * @param companyType
     * @return
     */
    private UserDTO getSaleMan(String companyType) {
        DispatchOrderRuleGetUserReq dispatchOrderRuleGetUserReq = new DispatchOrderRuleGetUserReq();
        dispatchOrderRuleGetUserReq.setBusinessTypeId(SystemBusinessType.OUTBOUND_CUSTOMIZATION.getCode());
        dispatchOrderRuleGetUserReq.setCompanyType(companyType);
        Result<Long> result = dispatchOrderRuleService.getDispatchUserId(dispatchOrderRuleGetUserReq);
        if (!result.isSuccess()) {
            throw new BusinessException(SystemError.getDefined(result.getCode()));
        }
        UserDTO saleUser = sysUserService.queryCacheUser(result.getData());
        return saleUser;
    }

    /**
     * 我的預約咨詢（C端）
     *
     * @param req
     * @return
     */
    @Override
    public PageResponse<ClientInquiryListDTO> list(ClientInquiryListReq req) {
        IPage<CustomizedInquiry> iPage = new Page<>(req.getPageNo(),req.getPageSize());
        QueryWrapper<CustomizedInquiry> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",req.getUserId());
        queryWrapper.eq("is_deleted",0);
        queryWrapper.orderByDesc("gmt_create");
        IPage<CustomizedInquiry> page = inquiryMapper.selectPage(iPage, queryWrapper);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return PageResponse.empty(page.getCurrent());
        }
        List<ClientInquiryListDTO> dtoList = new ArrayList<>();
        for (CustomizedInquiry inquiry : page.getRecords()){
            ClientInquiryListDTO dto = EntityUtil.copy(inquiry,ClientInquiryListDTO.class);
            dto.setGmtCreate(inquiry.getGmtCreate().toLocalDate());
            dtoList.add(dto);
        }
        PageResponse<ClientInquiryListDTO> result = new PageResponse<>(dtoList,
                page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()), page.getTotal(),
                page.getCurrent(), page.getSize());
        return result;
    }

    /**
     * 需求詳情（C端）
     *
     * @param req
     * @return
     */
    @Override
    public Result<ClientInquiryDetailDTO> detail(ClientInquiryDetailReq req) {
        CustomizedInquiry inquiry = inquiryMapper.selectById(req.getId());
        if (inquiry == null || Objects.equals(inquiry.getIsDeleted(),1)){
            throw new BusinessException(SystemError.ZLW_CUSTOM_ERROR_30001);
        }
        ClientInquiryDetailDTO dto = EntityUtil.copy(inquiry,ClientInquiryDetailDTO.class);
        //出行天数
        TravelDaysReq travelDaysReq = new TravelDaysReq();
        travelDaysReq.setDays(inquiry.getTravelDays());
        travelDaysReq.setNights(inquiry.getNightDays());
        dto.setTravelDaysReq(travelDaysReq);
        if (StringUtils.isNotBlank(inquiry.getInternalRemark())){
            InternalRemarkJson internalRemarkJson = null;
            try {
                internalRemarkJson = JSON.parseObject(inquiry.getInternalRemark(), InternalRemarkJson.class);
            }catch (Exception e){
                internalRemarkJson = new InternalRemarkJson();
                internalRemarkJson.setInternalRemark(inquiry.getInternalRemark());
                internalRemarkJson.setRequireList(JSON.parseArray(inquiry.getThemeJson(), InquiryRequireReq.class));
            }
            dto.setInternalRemarkJson(internalRemarkJson);
        }
        if (StringUtils.isNotBlank(inquiry.getDestinationJson())){
            List<ClientAreaDTO> destination = JSON.parseArray(inquiry.getDestinationJson(), ClientAreaDTO.class);
            dto.setDestination(destination);
        }
        //服务要求
        /*List<ServiceRequireDTO> serviceRequireDTOList = inquiryServiceRequireMapper.queryListByInquiryId(inquiry.getId());
        if (CollectionUtils.isNotEmpty(serviceRequireDTOList)){
            List<InquiryRequireReq> requireList = EntityUtil.copyList(serviceRequireDTOList,InquiryRequireReq.class);
            dto.setRequireList(requireList);
        }*/
        //询价单旅客数组
        List<QuotationTouristTypeReq> touristTypes = quotationTouristTypeMapper.queryByInquiry(inquiry.getId());
        dto.setTouristTypes(touristTypes);
        return Result.success(dto);
    }

    /**
     * 服务要求列表
     *
     * @return
     */
    @Override
    public List<ClientInquiryRequireListDTO> requireList() {
        MainDataRowFieldDataReq req = new MainDataRowFieldDataReq();
        req.setTid(1352181695073353730L);
        req.setFid(1352181925093179394L);
        List<MainDataRowFieldDataDTO> list = mainDataTableService.queryDataFieldLikeName(req);
        if (CollectionUtils.isNotEmpty(list)){
            return EntityUtil.copyList(list,ClientInquiryRequireListDTO.class);
        }
        return null;
    }

    /**
     * 通告列表（C端）
     *
     * @return
     */
    @Override
    public Result<List<ClientNoticeListDTO>> noticeList() {
        List<ClientNoticeListDTO> list = new ArrayList<>();
        /*BannerPositionByTypeReq req = new BannerPositionByTypeReq();
        req.setLinkType();
        req.setCode();
        List<NoticeDTO> noticeDTOS = noticeService.queryListByCode(req);*/
        ClientNoticeListDTO dto1 = new ClientNoticeListDTO();
        dto1.setContent("香港中旅社取消1月31日前往香港的旅游订单");
        list.add(dto1);
        ClientNoticeListDTO dto2 = new ClientNoticeListDTO();
        dto2.setContent("香港中旅社有望于9月底开始接香港旅游订单");
        list.add(dto2);
        return Result.success(list);
    }

    /**
     * 查询地区（C端）
     *
     * @param name
     * @return
     */
    @Override
    public Result<List<ClientAreaDTO>> area(String name) {
        AreaQueryReq req = new AreaQueryReq();
        req.setName(name);
        List<AreaDTO> areaDTOS = sysAreaService.queryListEs(req);
        if (CollectionUtils.isNotEmpty(areaDTOS)){
            List<ClientAreaDTO> list = EntityUtil.copyList(areaDTOS,ClientAreaDTO.class);
            return Result.success(list);
        }
        return Result.success(null);
    }

    /**
     * 手机短信查询
     *
     * @param inquiryNumber
     * @param queryNumber
     * @return
     */
    @Override
    public Long query(String inquiryNumber, String queryNumber) {
        if (StringUtils.isBlank(inquiryNumber) || StringUtils.isBlank(queryNumber)){
            throw new BusinessException(SystemError.SYS_402);
        }
        return inquiryMapper.query(inquiryNumber,queryNumber);
    }

}
